import { useCallback, useState, useEffect } from 'react';

type Props = {
   onDeleteCard: (id: string) => void;
};
const useMenuContext = ({ onDeleteCard }: Props) => {
   // 上下文菜单
   const [contextMenu, setContextMenu] = useState<{
      visible: boolean;
      cardId: string | null;
      position: { x: number; y: number };
   }>({
      visible: false,
      cardId: null,
      position: { x: 0, y: 0 },
   });
   const closeContextMenu = useCallback(() => {
      setContextMenu((prev) => ({ ...prev, visible: false }));
   }, []);

   const handleCardContextMenu = useCallback((e: React.MouseEvent, cardId: string) => {
      e.preventDefault();
      setContextMenu({
         visible: true,
         cardId,
         position: { x: e.clientX, y: e.clientY },
      });
   }, []);

   useEffect(() => {
      const handleClickOutside = () => {
         if (contextMenu.visible) {
            closeContextMenu();
         }
      };

      document.addEventListener('click', handleClickOutside);
      return () => {
         document.removeEventListener('click', handleClickOutside);
      };
   }, [contextMenu.visible, closeContextMenu]);

   const Menu = contextMenu.visible ? (
      <div
         className="context-menu"
         style={{
            left: contextMenu.position.x,
            top: contextMenu.position.y,
         }}
         onClick={(e) => e.stopPropagation()}
      >
         <div
            className="context-menu-item"
            onClick={() => {
               if (contextMenu.cardId) {
                  onDeleteCard(contextMenu.cardId);
               }
               closeContextMenu();
            }}
         >
            删除
         </div>
      </div>
   ) : null;

   return { Menu, handleCardContextMenu };
};

export default useMenuContext;
